<?php

class Default_IndexController extends Zend_Controller_Action 
{    
	public function preDispatch(){
		$session = new Zend_Session_Namespace('userAuth');
		$username='管理员';
		if(isset($session->username)){
			$username = $session->username;
		}
    	$this->view->username = $username;
    	$this->view->datetime = date('Y-m-d H:i:s');
	}
	
	public function indexAction()
    {
    	$session=new Zend_Session_Namespace('userAuth');
		if($session->userID){
			$res = parent::getFrontController()->getRequest()->getParams();
			$module = $res['module'];
			$controller = $res['controller'];
			$action = $res['action'];
			
			$check = Common_Service_Verfication::check($session->userID,$module,$controller,$action,'');
//			var_dump($check);exit();
			if(!$check){
				$this->_redirect('/index/nopermission');
				exit();
			}
		}

        if ($session->isLogin ) {           
            echo Cff::renderTpl('default/index/index.tpl',"layout");
        }else {        	
            $this->_redirect('/user/user/login');
        }
        exit;
    }
	
	public function rightMenuHeaderAction(){
		$params = parent::getFrontController()->getRequest()->getParams();
		$module = $params['module'];
		$controller = $params['controller'];
		$action = $params['action'];
		$actionRow = User_Service_Action::getRowByMCA($module,$controller,$action);
// 		print_r($this->lang);exit;
// 		$this->lang = Zend_Registry::get('lang');
		if(!($module=='default' && $controller=='index' && $action=='index')){
			$this->view->actionRow=$actionRow;
// 			print_r($actionRow);
			echo $this->view->render('default/index/rightMenuHeader.tpl');
		}
	}
	
	public function leftMenuAction(){
		$session=new Zend_Session_Namespace('userAuth');
		$lang = Zend_Registry::get('lang');
		$user_id = $session->userID;
		$mainMenuArr = $um_ur_Arr = $ur_urlArr = array();	
		if($user_id){
			$urm_rows = User_Service_RightMap::getRightByUserid($user_id);	// user_right_map 获取权限对应 
			$urIdArr = $urIdArr2 = array();
			foreach ($urm_rows as $key => $val){
				$urIdArr[] = $val['ur_id'];		//用户的所有right ID
			}
			
			//获取用户职位对应的默认权限
			$mapObj = new User_Service_PositionRightMap();
			$userInfo = User_Service_User::getByUserId($user_id);	//读取用户信息
			$positionRightsMap = $mapObj->getByPid($userInfo['up_id']);
			if(is_array($positionRightsMap) && $positionRightsMap){
				foreach ($positionRightsMap as $key =>$val){
					$urIdArr2[] = $val['ur_id'];
				}
				$urIdArr = array_merge($urIdArr,$urIdArr2);
				$urIdArr = array_unique($urIdArr);	//用户所有的 权限ID 
			}
			
			$count = User_Service_Menu::getCount();		//物流单号生成 页面的列表总数
			$ur_rows = User_Service_Right::getByCond(array(),'*','ur_id',0, 0);				
			//user_menu表um_title字段 相当于大类别，user_right表ur_name字段 为小类别
			foreach ($ur_rows as $key => $val){
				if( in_array($val['ur_id'],$urIdArr) ){
					$um_ur_Arr[$val['um_id']][$val['ur_id']] = $lang['current_language']=='cn'?$val['ur_name']:$val['ur_en_name'];		//菜单ID对应的right名称
					$ur_urlArr[$val['ur_id']] = $val['ur_url'];						// right ID对应的ur_url
				}
			}
			unset($um_ur_Arr[0]);	//default

			$umIdArr = array_keys($um_ur_Arr);		//菜单ID数组
			foreach ($umIdArr as $key => $val){
				$umRow = User_Service_Menu::getByUmid($val);
				$mainMenuArr[$val] = $lang['current_language']=='cn'?$umRow['um_title']:$umRow['um_en_title'];	//大类别 数组
			}
			
		}
// 		print_r($mainMenuArr);
// 		print_r($um_ur_Arr);exit;
		$this->view->count = $count;
		$this->view->um_ur_Arr = $um_ur_Arr;
		$this->view->ur_urlArr = $ur_urlArr;
		$this->view->mainMenuArr = $mainMenuArr;
		echo $this->view->render('default/index/leftmenu.tpl');
	}
	
	public function nopermissionAction(){
        $session=new Zend_Session_Namespace('userAuth');
        if(isset($session->userID)){
            $this->view->username = $session->username;
     	}
        echo $this->view->render('default/index/nopermission.tpl');
    }
    
	public function topAction(){

		echo $this->view->render('default/index/top.tpl');
	
	}
     public function loginAction() {
		$session = new Zend_Session_Namespace('userAuth');
		if($session->isLogin){
			$this->_redirect('/');
		}
		$errMsg ='';
        $this->view->errMsg = $errMsg;
		echo $this->view->render('user/user/login.tpl');
	}
	
	public function logoutAction() {
		$session = new Zend_Session_Namespace('userAuth');
		$session->unsetAll();
        session_destroy();
        //$_SESSION = array();//将所有在登录时保存的SESSION置空
        //unset($_SESSION);
        $errMsg = '';
        $this->view->errMsg = $errMsg;
		echo $this->view->render('user/user/login.tpl');
	}
	
	public function verifycodeAction() {
		$verifyCode = new Common_Service_Verifycode();
		$verifyCode->set_sess_name('UserVerifyCode');
		echo $verifyCode->render();
	}
	
	public function authenticateAction() {
		$ip = User_Service_User::getRealIp();
		$log = array();
		$errMsg ='';
		if ($this->_request->isPost()) {
			$username = $_POST['username'];
			$password = $_POST['password'];
			$verifyCode = $_POST['verifyCode'];
			//数据检查
			$sverifyCode = new Common_Service_Verifycode();
			$sverifyCode->set_sess_name('UserVerifyCode');
			
			if (!$sverifyCode->is_true($verifyCode)) {	//设置始终为false，即取消验证码
				$errMsg .=  $this->lang['verification_code'].$this->lang['error'] ;
                $log['status'] = 1;   //记录登陆信息状态
			}else {		//验证码正确
				
				$user = User_Service_User::getByLoginId($username);
				if(empty($user)){
					$errMsg .=$this->lang['user'].$this->lang['not_exists'];
                    $log['status'] = 2;
				}else {		//用户存在，继续验证密码
					if (Common_Service_Password::comparePassword($password, $user['passwd'])) {
                        $session = new Zend_Session_Namespace('userAuth');
                        $session->unsetAll();
                        
						//判断最近一次修改密码是否超过60天
						$date = date('Y-m-d');
						$user_date = $user['passwd_update_date'];
						$d1=strtotime($date);
						$d2=strtotime($user_date);
						$Days=round(($d1-$d2)/3600/24);	//计算相隔天数
						
						if(($Days >= 60) || $user['passwd_update_date'] == ''){
							$msgSession = new Zend_Session_Namespace('message');
							$msgSession->msg = $this->lang['long_time_no_change_pw'];
							$session->userID = $user['user_id'];
							$this->_redirect('/user/user/modifypassword');
							exit;
						}
						if ($user['status'] == '1') {	// status状态，0不激活，1激活
							 //login
                            $session->userID = $user['user_id'];
                            $session->username = $user['login_id'];
                            $session->name = $user['name'];
                            $session->last_update = $user['last_update'];
                            $session->login_date = date('Y-m-d');
                            $session->isLogin = true;
                            unset($user['passwd']);
                            $session->userInfo = $user;
                            
                            $this->view->user_id = $session->userID;
                            $this->view->username = $session->username;
                            $this->view->name = $session->name;
                          	
                            $userRow = array('last_login' => date('Y-m-d H:i:s'));
                            User_Service_User::update($userRow,$session->userID);	//更新最后登录时间
                            $log['status'] = 5;
                            
                            $this->_redirect("/");		//登陆成功
						}else {
							$errMsg .=  $this->lang['account_locked'] ;
                            $log['status'] = 3;
						}					
					}else {
						$errMsg .=  $this->lang['pw_error'] ;
                    	$log['status'] = 4;
					}
				
				}
						
			}

			$session = new Zend_Session_Namespace('userAuth');
			if(true == $session->isLogin){
        		$this->_redirect("/");
			}else{
				$this->view->errMsg = $errMsg;
				echo $this->view->render('user/user/login.tpl');
			}
		
		}
		echo $this->view->render('user/user/login.tpl');
	}


    public function csvDownAction(){
    	$name = trim($this->_request->getParam('name'));
    	if($name!="peachtao"){
    		die("非法用户");
    	}
    	$today = date("Y-m-d");
    	$date = trim($this->_request->getParam('date',$today));
    	$arr = array(
    			"o"=>"销售出库单",
    			"op"=>"销售出库产品",
    			"cu"=>"领用、借用单",
    			"cui"=>"领用、借用产品",
    			);
    	$fileName = trim($this->_request->getParam('f',"o"));
    	$filePath = APPLICATION_PATH . "/../data/" . $date."_".$fileName.".csv";
    	if(file_exists($filePath)){
    		header("Content-Type: APPLICATION/OCTET-STREAM");
    		//Force the download
    		$header="Content-Disposition: attachment; filename=".$arr[$fileName].".csv;";
    		header($header );
    		 
    		echo file_get_contents($filePath);
    	}else{
    		echo "file not exists";
    	}
    	
    	exit;
    	 
    }
    
    /**
     * 导入Action
     */
    public function toolAction(){
//     	exit;
        $tool = new Common_Service_ActionTool();
        $result = $tool->fenxi();
        print_r($result);exit;
    
    }
}